package com.ews.onlineexchange.controller;

import java.util.ArrayList;
import java.util.List;

import javax.enterprise.inject.Model;
import javax.persistence.EntityGraph;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.QualificationClass;
import com.ews.onlineexchange.model.ServiceDepartment;
import com.ews.onlineexchange.service.EntityQuery;

@Model
public class QualificationClassList extends EntityQuery<QualificationClass> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public QualificationClassList() {
		setMaxResults(null);
	}

	@Override
	protected Order[] getOrderArray(CriteriaBuilder cb, Root<QualificationClass> entity) {
		Order order = cb.asc(cb.function("gbk_order", String.class, entity.get("name")));
		return new Order[] {order};
	}

	@Override
	protected List<Predicate> getRestrictions(CriteriaBuilder cb, Root<QualificationClass> entity) {
		List<Predicate> restrictions = new ArrayList<Predicate>();
		restrictions.add( cb.equal( entity.get( "delFlag" ), QualificationClass.DEL_FLAG_NORMAL ) );
		String qualificationClassName = (String) getParameterValues().get( "qualificationClassName" );
		if ( !StringUtils.isBlank( qualificationClassName ) )
			restrictions.add( cb.like( entity.get( "name" ), getStringRestriction( qualificationClassName ) ) );

		String deptID = (String) getParameterValues().get( "deptID" );
		if ( !StringUtils.isBlank( deptID ) ) {
			Join<QualificationClass, ServiceDepartment> department = entity.join( "auditDepartment" );
			restrictions.add( cb.equal( department.get( "id" ), deptID ) );
		}
			
		return restrictions;
	}

	@Override
	protected void setHint( TypedQuery<QualificationClass> query ) {
		EntityGraph<?> entityGraph = entityManager.getEntityGraph( "QualificationClass.ServiceDepartment" );
		query.setHint( "javax.persistence.loadgraph", entityGraph );		
	}

	@Override
	protected void fetch(Root<QualificationClass> entity) {
		entity.fetch("levelOptions");
		entity.fetch("rootSectors");
	}

	@Override
	protected boolean isDistinct() {
		return true;
	}
	
	
}
